﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Text;

namespace CoolCode.Web.Mvc
{
    public static class ModelStateHelpers
    {
        public static void AddModelErrors(this ModelStateDictionary modelState, IEnumerable<RuleViolation> errors)
        {
            foreach (RuleViolation issue in errors)
            {
                modelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
            }
        }

    }

    public static class RouteDataHelpers
    {
        public static string GetInformation(this  System.Web.Routing.RouteData routeData)
        {
            if(routeData .Values.Count ==0)return string.Empty ;
            StringBuilder b = new StringBuilder();
            foreach (var data in routeData.Values)
                b.AppendFormat("{0}={1}&", data.Key, data.Value);
            return b.ToString(0, b.Length - 1);
        }
    }

    public static class ControllerHelpers
    {
        /// <summary> 
        /// 重定向到上一个Action. 即 header 的 "HTTP_REFERER"  (<c>Context.UrlReferrer</c>).
        /// </summary>
        public static RedirectResult RedirectToReferrer(this Controller controller)
        {
            return new RedirectResult(
                controller.Request.ServerVariables["HTTP_REFERER"]
                );
        }
        /// <summary> 
        /// Redirect 到站点根目录 (<c>Context.ApplicationPath + "/"</c>).
        /// </summary>
        public static RedirectResult RedirectToSiteRoot(this Controller controller)
        {
            return new RedirectResult(controller.Request.ApplicationPath + "/");
        }

        //public static Log BuildLog(this Controller controller, UserAction action, string message)
        //{
        //    Log log = new Log
        //    {
        //        Path = RequestUtility.GetUrl(),
        //        User = HttpContext.Current.User.Identity.Name,
        //        Time = DateTime.Now,
        //        Type = action.GetAttachedString(),
        //        Desc = message,
        //        From = RequestUtility.GetIP(),
        //        Name =RequestUtility.GetPageName(),
        //    };
        //    return log;
        //}
    }
}
